/**
 * ReportGear(2011)
 */
package com.reportgear.report.print;

import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.List;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

import net.abbp.core.utils.UnitUtils;

import com.reportgear.report.setting.PaperSetting;
import com.reportgear.report.setting.ReportSettings;

/**
 * 打印类
 * 
 * @version 1.0 2011-4-19
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class Printer {
    /**
     * 是否第一页，如果第一页打印，则弹出打印框
     * 
     * @param pages 所有页面
     */
    public void print(List<ReportPage> pages) {
        if (pages.isEmpty()) {
            return;
        }

        ReportSettings settings = pages.get(0).getReportModel().getReportSettings();

        PageFormat pageFormat = new PageFormat();

        PaperSetting paperSetting = settings.getPaperSetting();
        PaperSize paperSize = paperSetting.getPaperSize();
        Paper paper = pageFormat.getPaper();

        double ptWidth = UnitUtils.inch2pt(paperSize.getWidth());
        double ptHeight = UnitUtils.inch2pt(paperSize.getHeight());

        paper.setSize(ptWidth, ptHeight);

        paper.setImageableArea(0, 0, ptWidth, ptHeight);
        pageFormat.setPaper(paper);

        pageFormat.setOrientation(paperSetting.getOrientation());
        try {
            this.print(pages, pageFormat);
        } catch (PrinterException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 报表打印
     * 
     * @param pages 页面列表
     * @param format 格式
     * @param isFirst 是否第一页打印
     * @throws PrinterException
     *             打印异常
     */
    public void print(List<ReportPage> pages, PageFormat format) throws PrinterException {
        try {
            PrintService service = PrintServiceLookup.lookupDefaultPrintService();

            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPrintService(service);

            Book book = new Book();
            for (ReportPage page : pages) {
                book.append(page, format);
            }

            job.setPageable(book);
            job.validatePage(format);

            if (!job.printDialog()) {
                return;
            }

            job.print();
        } catch (PrinterException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 根据迭代器打印
     * 
     * @param reportPageIterator
     */
    public void print(ReportPageIterator reportPageIterator) {

    }
}
